
const {
    runLoaders
} = require("./loader-runner");
const path = require("path");
const fs = require("fs"); //webpack-dev-server启开发服务器的时候可能会用到 memory-fs模块
const entryFile = path.resolve(__dirname, "src/index.js");

// (    !	noAutoLoaders	        不要普通 loader     )
// (    -!	noPreAutoLoaders	    不要前置和普通 loader       )
// (    !!	noPrePostAutoLoaders	不要前后置和普通 loader,只要内联 loader     )
//配置行内loader
let request = `inline-loader1!inline-loader2!${entryFile}`;
// let request = `!!inline-loader1!inline-loader2!${entryFile}`; //noPrePostAutoLoaders
// let request = `-!!inline-loader1!inline-loader2!${entryFile}`; //noPreAutoLoaders
// let request = `!inline-loader1!inline-loader2!${entryFile}`; //noAutoLoaders

let rules = [{
        test: /\.js$/, //正常的loader
        use: ["normal-loader1", "normal-loader2"],
    },
    {
        test: /\.js$/,
        enforce: "post", //后置
        use: ["post-loader1", "post-loader2"],
    },
    {
        test: /\.js$/,
        enforce: "pre", //前置
        use: ["pre-loader1", "pre-loader2"],
    },
];

let parts = request.replace(/^-?!+/, '').split('!');
let resource = parts.pop() //弹出最后一个元素  entryfile
let inlineLoaders = parts //[inline-loader1,inline-loader2]
let preLoaders = [],
    postLoaders = [],
    normalLoaders = [];
for (let i = 0; i < rules.length; i++) {
    let rule = rules[i]
    if (rule.test.test(resource)) {
        if (rule.enforce === 'pre') {
            preLoaders.push(...rule.use);
        } else if (rule.enforce === 'post') {
            postLoaders.push(...rule.use);
        } else {
            normalLoaders.push(...rule.use);
        }
    }
}
let loaders = [];
if (request.startsWith('!!')) {
    loaders = [...inlineLoaders];
    //noPreAutoLoaders
} else if (request.startsWith('-!')) {
    loaders = [...postLoaders, ...inlineLoaders];
} else if (request.startsWith('!')) {
    //noAutoLoaders
    loaders = [...postLoaders, ...inlineLoaders, ...preLoaders];
} else {
    loaders = [...postLoaders, ...inlineLoaders, ...normalLoaders, ...preLoaders];
}
let resolveLoader = loader => path.resolve(__dirname, 'loaders-chain', loader)
//把loader数组从名称变成绝对路径
loaders = loaders.map(resolveLoader);
debugger
// console.log(loaders)
runLoaders({
    resource, //要加载的资源
    loaders,
    context: {
        name: 'ikki',
        age: 100
    }, //保存一些状态和值 
    readResource: fs.readFile.bind(this)
}, (err, result) => {
    console.log(err); //运行错误
    console.log('result', result); //运行的结果
    console.log(result.resourceBuffer ? result.resourceBuffer.toString('utf8') : null); //读到的原始的文件
})